from app import dBSession
from sqlalchemy import desc, asc, and_
from app.Models.BaseModel import BaseModel
from sqlalchemy_serializer import SerializerMixin
from app.Vendor.Decorator import classTransaction
from app.Models.Model import ReactionPair


class ReactionPairs(ReactionPair, BaseModel, SerializerMixin):
    def getOne(self, filters, order='id desc', field=()):
        res = dBSession.query(ReactionPairs).filter(*filters)
        order = order.split(' ')
        if order[1] == 'desc':
            res = res.order_by(desc(order[0])).first()
        else:
            res = res.order_by(asc(order[0])).first()
        if res == None:
            return None
        if not field:
            res = res.to_dict()
        else:
            res = res.to_dict(only=field)
        return res

    def getAll(self, filters, order='id desc', field=()) -> list:
        """
        查询全部
        @param object cls_ 数据库模型实体类
        @param set filters 查询条件
        @param str order 排序
        @param tuple field 字段
        @param int $limit 取多少条
        @return dict
        """
        if not filters:
            res = dBSession.query(ReactionPairs)
        else:
            res = dBSession.query(ReactionPairs).filter(*filters)
        orderArr = order.split(' ')
        if orderArr[1] == 'desc':
            res = res.order_by(desc(orderArr[0])).all()
        else:
            res = res.order_by(asc(orderArr[0])).all()
        if not field:
            res = [c.to_dict() for c in res]
        else:
            res = [c.to_dict(only=field) for c in res]
        return res

    def getList(self, interaction_list, cpdImformations):
        res = {}

        # 将interaction_list中所有的cpd对进行查询可能对应的reaction，并添加到res中
        for i in interaction_list:
            r = self.getAll(
                {
                    and_(ReactionPairs.compound1 == i[0], ReactionPairs.compound2 == i[1])
                }
            )
            for single_r in r:
                res[single_r['reaction']] = [single_r['reaction'], i[0], i[1]]
        return res
